package com.qingmeng.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.qingmeng.apiclientsdk.client.ApiClient;
import com.qingmeng.apiclientsdk.config.ApiMethodConfig;
import com.qingmeng.apiclientsdk.dto.RequestParams;
import com.qingmeng.apiclientsdk.entry.ApiResponse;
import com.qingmeng.apicommon.common.*;
import com.qingmeng.apicommon.model.entity.InterfaceInfo;
import com.qingmeng.apicommon.model.entity.User;
import com.qingmeng.project.annotation.Anonymous;
import com.qingmeng.project.annotation.AuthCheck;
import com.qingmeng.apicommon.constant.SortConstant;
import com.qingmeng.apicommon.exception.BusinessException;
import com.qingmeng.project.model.dto.interfaceInfo.InterfaceInfoAddRequest;
import com.qingmeng.project.model.dto.interfaceInfo.InterfaceInfoQueryRequest;
import com.qingmeng.project.model.dto.interfaceInfo.InterfaceInfoTextRequest;
import com.qingmeng.project.model.dto.interfaceInfo.InterfaceInfoUpdateRequest;
import com.qingmeng.project.model.enums.InterfaceInfoStatusEnum;
import com.qingmeng.project.service.InterfaceInfoService;
import com.qingmeng.project.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接口管理
 *
 * @author qingmeng
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
@Api(tags = "接口信息管理")
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;

    @Resource
    private ApiClient apiClient;

    // region 增删改查

    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @Anonymous
    @Operation(summary = "创建接口信息", description = "创建一个新的接口信息")
    public BaseResponse<Long> addInterfaceInfo(
            @Parameter(description = "接口信息添加请求") @RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest,
            @Parameter(hidden = true) HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        // 校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setCreateBy(loginUser.getId());
        boolean result = interfaceInfoService.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @Operation(summary = "删除接口信息", description = "根据ID删除接口信息")
    public BaseResponse<Boolean> deleteInterfaceInfo(
            @Parameter(description = "删除请求") @RequestBody DeleteRequest deleteRequest,
            @Parameter(hidden = true) HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getCreateBy().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param interfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @Operation(summary = "更新接口信息", description = "根据ID更新接口信息")
    public BaseResponse<Boolean> updateInterfaceInfo(
            @Parameter(description = "接口信息更新请求") @RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
            @Parameter(hidden = true) HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);

        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        User user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();
        interfaceInfo.setUpdateBy(user.getId());
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getCreateBy().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @Anonymous
    @Operation(summary = "获取接口信息", description = "根据ID获取接口信息")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(
            @Parameter(description = "接口信息ID") @RequestParam long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    @Anonymous
    @Operation(summary = "获取接口信息列表", description = "获取所有接口信息列表（仅管理员可使用）")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(
            @Parameter(description = "接口信息查询请求") @RequestParam(required = false) InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    @Anonymous
    @Operation(summary = "分页获取接口信息列表", description = "分页获取接口信息列表")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(
            @Parameter(description = "接口信息查询请求") @RequestParam InterfaceInfoQueryRequest interfaceInfoQueryRequest,
            @Parameter(hidden = true) HttpServletRequest request) {
        // 检查请求对象是否为空，如果为空则抛出参数错误异常
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 创建一个新的 InterfaceInfo 对象用于查询
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        // 将请求对象中的属性复制到查询对象中
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);

        // 获取当前页码和页面大小
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        // 获取排序字段和排序顺序
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        // 获取描述内容，用于模糊搜索
        String content = interfaceInfoQuery.getDescription();

        // Description 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);

        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 创建查询包装器
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        // 如果内容不为空，则添加模糊搜索条件
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        // 添加排序条件
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(SortConstant.SORT_ORDER_ASC), sortField);

        // 执行分页查询
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);

        // 返回查询结果
        return ResultUtils.success(interfaceInfoPage);
    }

    /**
     * 上线接口
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/onLine")
    @AuthCheck(mustRole = "admin")
    @Operation(summary = "上线接口", description = "根据ID上线接口")
    public BaseResponse<Boolean> OnLineInterfaceInfo(
            @Parameter(description = "根据id请求") @RequestBody IdRequest idRequest,
            @Parameter(hidden = true) HttpServletRequest request) throws UnsupportedEncodingException {

        // 1、 判断参数是否存在
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2、 校验接口是否存在
        //接收请求中的参数
        Long id = idRequest.getId();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw   new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 3、 判断接口是否可以调用
        com.qingmeng.apiclientsdk.entry.User user = new com.qingmeng.apiclientsdk.entry.User();
        user.setUserName("测试");
        // todo 根据用户提供的地址去调用接口，检测接口是否可以使用
//        Response response = apiClient.getNameByJson(user);
//        if (StringUtils.isBlank(response.getMessage())){
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口调用失败");
//        }

        // 4、修改接口的数据库的状态
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }
    /**
     * 下线接口
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/offLine")
    @AuthCheck(mustRole = "admin")
    @Operation(summary = "下线接口", description = "根据ID下线接口")
    public BaseResponse<Boolean> OffLineInterfaceInfo(
            @Parameter(description = "根据id请求") @RequestBody IdRequest idRequest,
            @Parameter(hidden = true) HttpServletRequest request) {
        // 1、 判断参数是否存在v
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2、 校验接口是否存在
        //接收请求中的参数
        Long id = idRequest.getId();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw   new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 3、修改接口的数据库的状态
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.OFFLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 测试接口
     *
     * @param interfaceInfoTextRequest
     * @param request
     * @return
     */
    @PostMapping("/TextInterface")
    @Operation(summary = "测试接口", description = "根据ID测试接口")
    public BaseResponse<Object> Text2InterfaceInfo(
            @Parameter(description = "根据id请求") @RequestBody InterfaceInfoTextRequest interfaceInfoTextRequest,
            @Parameter(hidden = true) HttpServletRequest request) {
        // 1、 判断参数是否存在
        if (interfaceInfoTextRequest == null || interfaceInfoTextRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2、接收请求中的参数
        Long id = interfaceInfoTextRequest.getId();
        String userRequestParams = interfaceInfoTextRequest.getUserRequestParams();
        // 打印用户填写的请求参数
        log.info("用户填写的请求参数为：{}", userRequestParams);
        // 3、判断接口是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw   new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 4、检查接口是否为下线状态
        if (oldInterfaceInfo.getStatus() == InterfaceInfoStatusEnum.OFFLINE.getValue()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口已关闭");
        }
        // 5、获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        //6、获取当前用户的AK、SK
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        ApiClient textApiClient = new ApiClient(accessKey, secretKey);
        //7、创建一个JSON解析对象，解析用户传递过来的参数
        Gson gson = new Gson();
        com.qingmeng.apiclientsdk.entry.User user = gson.fromJson(userRequestParams, com.qingmeng.apiclientsdk.entry.User.class);
        // 7.5 展示一下解析后的user
        System.out.println(user);
        // 8、todo 这里应该根据接口的id 去调用接口，但是这里为了方便，直接调用本地接口
        try {
            String url = oldInterfaceInfo.getUrl();
            log.info("用户访问的接口地址为：{}", url);
            RequestParams<com.qingmeng.apiclientsdk.entry.User> userRequestParams1 = new RequestParams<>();
            userRequestParams1.setUrl(url);
            userRequestParams1.setBody(user);

            //设置用户的请求url，和对应的请求方法
            ApiMethodConfig apiMethodConfig = new ApiMethodConfig();
            Map<String, String> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put(url, "getNameByJson");
            apiMethodConfig.setMethods(objectObjectHashMap);

            ApiResponse<?> jsonResponse = textApiClient.invokeMethod(apiMethodConfig,userRequestParams1);
            System.out.println("JSON Response: " + jsonResponse);

            // 7、返回响应

            return ResultUtils.success(jsonResponse);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
